package com.cacho.s2b.lesson.util;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.FileReader;
import java.io.Reader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Getter
@Setter
public class CsvUtils {
    private CSVReader reader;
    private int rowSize; //行长度
    private int columnSize;// 列长度
    private String logName = "CSV File"; // 文件名称
    private List<String[]> entries = new ArrayList<>(); // 列表数组所有csv文件内容
    private List<Integer> ignoreRowLines; // 忽略的行
    private List<Map<String, String>> dataMaps = new ArrayList<>(); // map对象列表
    private Map<String, String> mapColumn = new HashMap<>(); // map对象(针对接口字段mapping)

    public static void main(String[] args) {
        String csvFilePath = "F:\\JavaProject\\api_def.csv";
        CsvUtils csv = new CsvUtils(csvFilePath);
        csv.ToListMap();
        System.out.println(csv.getDataMaps());
        System.out.println("不符合规则的行号列表：" + csv.getIgnoreRowLines());
    }

    // 传入一个绝对路径的文件 "F:\\JavaProject\\api_def.csv"
    public CsvUtils(String csvFilePath) {
        this.logName = csvFilePath;
        try {
            this.reader = new CSVReader(new FileReader(csvFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 传入一个相对路径的文件 "F:\\JavaProject\\api_def.csv"
    public CsvUtils(InputStream in, String logName) {
        this.logName = logName;
        Reader re = null;
        re = new InputStreamReader(in, StandardCharsets.UTF_8);
        this.reader = new CSVReader(re);
    }

    // 如果entries没有赋值，重新readAll()组装成一个 list的 map 对象
    public void ToListMap() {
        try {
            if (entries.isEmpty()) {
                entries = this.reader.readAll();
            }
        } catch (IOException | CsvException e) {
            e.printStackTrace();
        }
        this.rowSize = entries.size();
        this.columnSize = entries.get(0).length; // 第一行title对应长度
        String[] keys = entries.get(0); // 第一行title数组
        ignoreRowLines = new ArrayList<>();
        // 第二行开始
        for (int i = 1; i < this.rowSize; i++) {
            String[] e = entries.get(i); // 行数组信息
            if (e.length == columnSize) {
                Map<String, String> map = new HashMap<>();
                this.dataMaps.add(map);
                for (int j = 0; j < columnSize; j++) {
                    String key = keys[j]; // title值遍历
                    map.put(key, e[j]);
                }
            } else {
                log.warn("忽略无效的行数{} 数据{} 在文件{}里", i + 1, String.join(",", e), logName);
                ignoreRowLines.add(i + 1);
            }
        }
    }
    public void ToMap(String colKey, String colValue) throws Exception {
        mapColumn = new HashMap<>();
        this.ToListMap();
        for (Map<String, String> dataMap : dataMaps) {
            if(!dataMap.containsKey(colKey)){
                throw new Exception("Csv Header not found:"+colKey);
            }
            if(!dataMap.containsKey(colValue)){
                throw new Exception("Csv Header not found:"+colValue);
            }
            mapColumn.put(dataMap.get(colKey),dataMap.get(colValue));
        }
    }
}
